/*
 * Copyright (c) 2009-2010 HIT Microelectronic Center
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * Authors: Gou Pengfei
 *          Jin Yinghan
 *
 * Date: Dec. 2009
 *
 */

#ifndef __CPU_EDGE_EdgeROB_HH__
#define __CPU_EDGE_EdgeROB_HH__

#include <string>
#include <utility>
#include <vector>

#include "config/the_isa.hh"

/**
 * EdgeROB class.  The EdgeROB is largely what drives squashing.
 */
template <class Impl>
class EdgeROB
{
  protected:
    typedef TheISA::RegIndex RegIndex;
  public:
    //Typedefs from the Impl.
    typedef typename Impl::CPU CPU;
    typedef typename Impl::DynInstPtr DynInstPtr;
    typedef typename Impl::EdgeBlockPtr EdgeBlockPtr;

    //typedef std::pair<RegIndex, PhysRegIndex> UnmapInfo;
    typedef typename std::list<DynInstPtr>::iterator InstIt;
    typedef typename std::list<EdgeBlockPtr>::iterator InstBlockIt;

    /** Possible EdgeROB statuses. */
    enum Status {
        Running,
        Idle,
        EdgeROBSquashing
    };

    /** SMT EdgeROB Sharing Policy */
    enum EdgeROBPolicy{
        Dynamic,
        Partitioned,
        Threshold
    };

  private:
    /** Per-thread EdgeROB status. */
    Status robStatus[Impl::MaxThreads];

    /** EdgeROB resource sharing policy for SMT mode. */
    EdgeROBPolicy robPolicy;

  public:
    /** EdgeROB constructor.
     *  @param _numEntries      Number of entries in EdgeROB.
     *  @param _squashWidth     Number of instructions that can be squashed in a
     *                          single cycle.
     *  @param _smtEdgeROBPolicy    EdgeROB Partitioning Scheme for SMT.
     *  @param _smtEdgeROBThreshold Max Resources(by %) a thread can have in the EdgeROB.
     *  @param _numThreads      The number of active threads.
     */
    EdgeROB(CPU *_cpu, unsigned _numEntries, unsigned _squashWidth,
        std::string smtEdgeROBPolicy, unsigned _smtEdgeROBThreshold,
        ThreadID _numThreads);

    std::string name() const;

    /** Sets pointer to the list of active threads.
     *  @param at_ptr Pointer to the list of active threads.
     */
    void setActiveThreads(std::list<ThreadID> *at_ptr);

    /** Switches out the EdgeROB. */
    void switchOut();

    /** Takes over another CPU's thread. */
    void takeOverFrom();

    /** Function to insert an instruction into the EdgeROB. Note that whatever
     *  calls this function must ensure that there is enough space within the
     *  EdgeROB for the new instruction.
     *  @param inst The instruction being inserted into the EdgeROB.
     */
    void insertInstBlock(EdgeBlockPtr &inst_block);

    /** Returns a pointer to the head instruction of a specific thread within
     *  the EdgeROB.
     *  @return Pointer to the DynInst that is at the head of the EdgeROB.
     */
    EdgeBlockPtr readHeadInstBlock(ThreadID tid);

    /**
     * Returns the block ID of head inst block.
    */
    TheISA::BlockID readHeadInstBlockID(ThreadID tid);

    /** Returns a pointer to the tail instruction of a specific thread within
     *  the EdgeROB.
     *  @return Pointer to the DynInst that is at the tail of the EdgeROB.
     */
    EdgeBlockPtr readTailInstBlock(ThreadID tid);

    /** Retires the head instruction of a specific thread, removing it from the
     *  EdgeROB.
     */
    void retireHead(ThreadID tid);

    /** Is the oldest instruction across a particular thread ready. */
    bool isHeadReady(ThreadID tid);

    /** Is there any commitable head instruction across all threads ready. */
    bool canCommit();

    /** Re-adjust EdgeROB partitioning. */
    void resetEntries();

    /** Number of entries needed For 'num_threads' amount of threads. */
    int entryAmount(ThreadID num_threads);

    /** Returns the number of total free entries in the EdgeROB. */
    unsigned numFreeEntries();

    /** Returns the number of free entries in a specific EdgeROB paritition. */
    unsigned numFreeEntries(ThreadID tid);

    /** Returns the maximum number of entries for a specific thread. */
    unsigned getMaxEntries(ThreadID tid)
    { return maxEntries[tid]; }

    /** Returns the number of entries being used by a specific thread. */
    unsigned getThreadEntries(ThreadID tid)
    { return threadEntries[tid]; }

    /** Returns if the EdgeROB is full. */
    bool isFull()
    { return numInstBlocksInEdgeROB == numEntries; }

    /** Returns if a specific thread's partition is full. */
    bool isFull(ThreadID tid)
    { return threadEntries[tid] == numEntries; }

    /** Returns if the EdgeROB is empty. */
    bool isEmpty()
    { return numInstBlocksInEdgeROB == 0; }

    /** Returns if a specific thread's partition is empty. */
    bool isEmpty(ThreadID tid)
    { return threadEntries[tid] == 0; }

    /** Executes the squash, marking squashed instructions. */
    int doSquash(ThreadID tid);

    /** Squashes all instructions younger than the given sequence number for
     *  the specific thread. Return the number of squashed inst
     *  blocks.
     */
    int squash(TheISA::BlockID squash_num, ThreadID tid);

    /** Updates the head instruction with the new oldest instruction. */
    void updateHead();

    /** Updates the tail instruction with the new youngest instruction. */
    void updateTail();

    /** Checks if the EdgeROB is still in the process of squashing instructions.
     *  @retval Whether or not the EdgeROB is done squashing.
     */
    bool isDoneSquashing(ThreadID tid) const
    { return doneSquashing[tid]; }

    /** Checks if the EdgeROB is still in the process of squashing instructions for
     *  any thread.
     */
    bool isDoneSquashing();

    /** This is more of a debugging function than anything.  Use
     *  numInstBlocksInEdgeROB to get the instructions in the EdgeROB unless you are
     *  double checking that variable.
     */
    int countInstBlocks();

    /** This is more of a debugging function than anything.  Use
     *  threadEntries to get the instructions in the EdgeROB unless you are
     *  double checking that variable.
     */
    int countInstBlocks(ThreadID tid);

  private:
    /** Pointer to the CPU. */
    CPU *cpu;

    /** Active Threads in CPU */
    std::list<ThreadID> *activeThreads;

    /** Number of instructions in the EdgeROB. */
    unsigned numEntries;

    /** Entries Per Thread */
    unsigned threadEntries[Impl::MaxThreads];

    /** Max Insts a Thread Can Have in the EdgeROB */
    unsigned maxEntries[Impl::MaxThreads];

    /** EdgeROB List of Instructions */
    std::list<EdgeBlockPtr> instBlockList[Impl::MaxThreads];

    /** Number of instructions that can be squashed in a single cycle. */
    unsigned squashWidth;

  public:
    /** Iterator pointing to the instruction which is the last instruction
     *  in the EdgeROB.  This may at times be invalid (ie when the EdgeROB is empty),
     *  however it should never be incorrect.
     */
    InstBlockIt tail;

    /** Iterator pointing to the instruction which is the first instruction in
     *  in the EdgeROB*/
    InstBlockIt head;

  private:
    /** Iterator used for walking through the list of instructions when
     *  squashing.  Used so that there is persistent state between cycles;
     *  when squashing, the instructions are marked as squashed but not
     *  immediately removed, meaning the tail iterator remains the same before
     *  and after a squash.
     *  This will always be set to cpu->instList.end() if it is invalid.
     */
    InstBlockIt squashIt[Impl::MaxThreads];

  public:
    /** Number of instructions in the EdgeROB. */
    int numInstBlocksInEdgeROB;

    /** Dummy instruction returned if there are no insts left. */
    EdgeBlockPtr dummyInstBlock;

  private:
    /** The sequence number of the squashed instruction. */
    TheISA::BlockID squashedSeqNum[Impl::MaxThreads];

    /** Is the EdgeROB done squashing. */
    bool doneSquashing[Impl::MaxThreads];

    /** Number of active threads. */
    ThreadID numThreads;
};

#endif //__CPU_EDGE_ROB_HH__
